package com.atguigu.preparedstatement.crud;

import com.atguigu.util.JDBCUtils;
import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;

// 更高效的批量插入操作
public class InsertTest {
    @Test
    public void testInsert () {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = JDBCUtils.getConnection();
            String sql = "insert into goods(name)values(?)";
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < 20000; ++i) {
                ps.setObject(1, "name_" + i);
                ps.execute();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(conn, ps);
        }
        
    }

    @Test
    public void testInsert2 () {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = JDBCUtils.getConnection();
            String sql = "insert into goods(name)values(?)";
            ps = conn.prepareStatement(sql);
            for (int i = 1; i <= 100; ++i) {
                ps.setObject(1, "name_" + i);
                ps.addBatch();
                if (i % 5 == 0)
                {
                    ps.executeBatch();
                    ps.clearBatch();
                    System.out.println(i);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(conn, ps);
        }

    }

    @Test
    public void testInsert3 () {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = JDBCUtils.getConnection();
            conn.setAutoCommit(false); // 不允许自动提交
            String sql = "insert into goods(name)values(?)";
            ps = conn.prepareStatement(sql);
            for (int i = 1; i <= 100; ++i) {
                ps.setObject(1, "name_" + i);
                ps.addBatch();
                if (i % 5 == 0)
                {
                    ps.executeBatch();
                    ps.clearBatch();
                    System.out.println(i);
                }
            }
            conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(conn, ps);
        }

    }


}
